/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.discoveryservice.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.ourgrid.common.interfaces.DiscoveryService;
import org.ourgrid.common.interfaces.DiscoveryServiceClient;
import org.ourgrid.discoveryservice.DiscoveryServiceConstants;
import org.ourgrid.discoveryservice.PeerStatusChangeUtil;
import org.ourgrid.discoveryservice.config.DiscoveryServiceConfiguration;
import org.ourgrid.discoveryservice.controller.messages.DiscoveryServiceControlMessages;
import org.ourgrid.discoveryservice.dao.DiscoveryServiceDAO;

import br.edu.ufcg.lsd.commune.api.FailureNotification;
import br.edu.ufcg.lsd.commune.api.InvokeOnDeploy;
import br.edu.ufcg.lsd.commune.api.MonitoredBy;
import br.edu.ufcg.lsd.commune.api.RecoveryNotification;
import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;
import br.edu.ufcg.lsd.commune.identification.ServiceID;

public class DiscoveryServiceController implements DiscoveryService {

	private ServiceManager serviceManager;

	@InvokeOnDeploy
	public void init(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}
	
	private void joinCommunity(DiscoveryServiceClient dsClient, DeploymentID dsClientDID) {
		
		boolean modified = serviceManager.getDAO(DiscoveryServiceDAO.class).peerIsUp(dsClientDID.getContainerID().getUserAtServer());
		DiscoveryServiceDAO discoveryServiceDAO = serviceManager.getDAO(DiscoveryServiceDAO.class);
		
		if (modified) {
			List<String> onlinePeers = discoveryServiceDAO.getOnlinePeers();
			Map<ServiceID,DiscoveryService> discoveryServiceMap = discoveryServiceDAO.getDiscoveryServicesMap();
			for (Entry<ServiceID,DiscoveryService> entry : discoveryServiceMap.entrySet()) {
				entry.getValue().hereIsRemoteWorkerProviderList( onlinePeers );
			}
		}
		
		PeerStatusChangeUtil.peerIsUp(dsClientDID);
		
	}
	
	public void leaveCommunity(@MonitoredBy(DiscoveryServiceConstants.DS_OBJECT_NAME) DiscoveryServiceClient dsClient) {
		DeploymentID dsClientDID = serviceManager.getStubDeploymentID(dsClient);
		
		DiscoveryServiceDAO dao = serviceManager.getDAO(DiscoveryServiceDAO.class);
		
		if (!dao.isLogged(dsClientDID.getUserName() + "@" + dsClientDID.getServerName())) {
			serviceManager.getLog().warn(DiscoveryServiceControlMessages.getClientNotJoinedToTheCommunityMessage(dsClientDID));
			serviceManager.release(dsClient);
			return;
		}
		
		dao.peerIsDown(dsClientDID.getContainerID().getUserAtServer());
		
		serviceManager.release(dsClient);
		
		PeerStatusChangeUtil.peerIsDown(dsClientDID);
	}
	
	public void getRemoteWorkerProviders( @MonitoredBy(DiscoveryServiceConstants.DS_OBJECT_NAME) DiscoveryServiceClient dsClient ) {
		
		DiscoveryServiceDAO dsDao = serviceManager.getDAO(DiscoveryServiceDAO.class);
		
		DeploymentID dsClientDID = serviceManager.getStubDeploymentID(dsClient);
		String clientUserAtServer = dsClientDID.getContainerID().getUserAtServer();
		
		if (!dsDao.isLogged(clientUserAtServer)) {
			serviceManager.getLog().debug(
					DiscoveryServiceControlMessages.getClientNotLoggedMessage(clientUserAtServer));
			joinCommunity(dsClient, dsClientDID);
		}
		
		dsClient.hereIsRemoteWorkerProviderList(dsDao.getOnlinePeers());
	}
	
	@RecoveryNotification
	public void dsClientIsUp(DiscoveryServiceClient discoveryServiceClient, DeploymentID providerDID) {
		serviceManager.getDAO(DiscoveryServiceDAO.class).peerIsUp(providerDID.getContainerID().getUserAtServer());
	}

	@FailureNotification
	public void dsClientIsDown(DiscoveryServiceClient discoveryServiceClient, DeploymentID monitorableID) {
		
		DiscoveryServiceDAO dao = serviceManager.getDAO(DiscoveryServiceDAO.class);
		serviceManager.release(discoveryServiceClient);
		
		if (monitorableID == null) {
			serviceManager.getLog().error(DiscoveryServiceControlMessages.getNullMonitorableIDMessage());
			return;
		}
		
		dao.peerIsDown(monitorableID.getContainerID().getUserAtServer());
		
		PeerStatusChangeUtil.peerIsDown(monitorableID);
	}
	
	public void getDiscoveryServices(@MonitoredBy(DiscoveryServiceConstants.DS_MONITOR) DiscoveryService discoveryService) {
		
		DiscoveryServiceDAO discoveryServiceDAO = serviceManager.getDAO(DiscoveryServiceDAO.class);
		ServiceID serviceID = serviceManager.getStubDeploymentID(discoveryService).getServiceID();
		boolean modified = discoveryServiceDAO.putDiscoveryService(serviceID, discoveryService);
		if (modified){
			try {
				DiscoveryServiceConfiguration.persistNetwork(discoveryServiceDAO.getDiscoveryServicesAddresses(), 
						serviceManager.getContainerContext());
			} catch (IOException e) {
				serviceManager.getLog().error("Properties file could not be written with new Discovery Services Address", e);
			}
		}

		serviceManager.getLog().info(
				"DiscoveryServiceController.getDiscoveryServices() at "
						+ serviceManager.getMyDeploymentID().getServiceID() + " by "
						+ serviceManager.getStubDeploymentID( discoveryService ).getServiceID() );
		discoveryService.hereAreDiscoveryServices(discoveryServiceDAO.getDiscoveryServicesIDs());
	}

	public void hereAreDiscoveryServices(List<ServiceID> discoveryServicesID) {
		
		for (ServiceID serviceID : discoveryServicesID) {
			serviceManager.registerInterest(DiscoveryServiceConstants.DS_MONITOR, 
					serviceID.toString(), DiscoveryService.class);
		}
	}

	public void getDiscoveryServices( @MonitoredBy(DiscoveryServiceConstants.DS_OBJECT_NAME) DiscoveryServiceClient discoveryServiceClient) {
		discoveryServiceClient.hereAreDiscoveryServices(serviceManager.getDAO(DiscoveryServiceDAO.class).getDiscoveryServicesAddresses());
	}

	public void hereIsRemoteWorkerProviderList( List<String> workerProviders ) {

		ServiceID senderServiceID = serviceManager.getSenderServiceID();
		DiscoveryServiceDAO discoveryServiceDAO = serviceManager.getDAO( DiscoveryServiceDAO.class );
		List<String> oldList = discoveryServiceDAO.getOnlinePeers();
		boolean modified = oldList.removeAll( workerProviders );
		
		for ( String downPeerAddress : oldList ) {
			discoveryServiceDAO.peerIsDown( downPeerAddress );
		}
		
		for (String workerProvider : workerProviders) {
			modified |= discoveryServiceDAO.peerIsUp( workerProvider );
		}
		
		if(modified){
			List<String> onlinePeers = discoveryServiceDAO.getOnlinePeers();
			Map<ServiceID,DiscoveryService> discoveryServiceMap = discoveryServiceDAO.getDiscoveryServicesMap();
			for (Entry<ServiceID,DiscoveryService> entry : discoveryServiceMap.entrySet()) {
				if(!entry.getKey().equals( senderServiceID )){
					entry.getValue().hereIsRemoteWorkerProviderList( onlinePeers );
				}
			}
		}
	}
}
